package com.googlecode.horncomb.web.spring.context;

import java.io.IOException;
import java.util.logging.LogRecord;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class WebApplicationContextLocatorFilter implements Filter,
		java.util.logging.Filter {
	private static Log log = LogFactory
			.getLog(WebApplicationContextLocatorFilter.class);

	public void init(FilterConfig config) throws ServletException {
		// do nothing;
	}

	public void destroy() {
		LocalApplicationContextLocator.setApplicationContext(null);
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		try {
			if (request instanceof HttpServletRequest) {
				WebApplicationContext ctx = WebApplicationContextUtils
						.getRequiredWebApplicationContext(((HttpServletRequest) request)
								.getSession().getServletContext());
				LocalApplicationContextLocator.setApplicationContext(ctx);
				log.debug("get ApplicationContext: " + ctx);
			}
			chain.doFilter(request, response);
		} finally {
			LocalApplicationContextLocator.setApplicationContext(null);
		}
	}

	public boolean isLoggable(LogRecord record) {
		return false;
	}
}
